import { Injectable } from '@angular/core';
import { Storage } from '@ionic/Storage';
import { Observable, Subject } from 'rxjs';
import { apiUrls } from './config';
import { MessageService } from './message.service';

const subject: Subject<any> = new Subject<any>();

@Injectable({
  providedIn: 'root',
})
export class CacheService {
  _configs;
  _clientKey;
  _clientToken;
  _upwd;
  _defaultVoice: { voiceType: any, voiceName: any };
  _userinfo: any;
  _userimg: any;
  _companys: any;
  _functionPoint: any;
  _currentCompany: any;
  _currentProject: any;
  _install: any;
  _stack: any;
  _headPortrait: { oldAvatar: string, avatar: string };
  _edition: { appVersion: any, label: string };

  constructor(public storage: Storage,
    private messageService: MessageService
  ) {
    this._configs = apiUrls.data;
  }

  public get currentIndexPage(): Observable<any> {
    return this.getCurrentIndexPage();
  }

  get apiConfig(): Observable<any> {
    return new Observable(responseObserver => {
      if (this._configs) {
        responseObserver.next(this._configs);
      } else {
        this.storage.get('_configs').then(data => {
          this._configs = data;
          responseObserver.next(data);
          responseObserver.complete();
        });
      }
    });
  }

  set apiConfig(value) {
    this._configs = value;
    this.storage.set('_configs', value);
  }

  get clientToken(): Observable<any> {
    return new Observable(responseObserver => {
      if (this._clientToken) {
        responseObserver.next(this._clientToken);
      } else {
        this.storage.get('_clientToken').then(data => {
          responseObserver.next(data);
          responseObserver.complete();
        });
      }
    });
    // return this.getLocalstorageValue('clientToken');
  }

  set clientToken(value) {
    this._clientToken = value;
    this.storage.set('_clientToken', value);
    // this.setLocalstorageValue('clientToken', value);
  }

  getClientToken() {
    return this._clientToken;
  }

  // App版本信息（同步返回）
  get edition() {
    return this.getLocalstorageValue('edition');
  }
  set edition(value) {
    this.setLocalstorageValue('edition', value);
  }

   // 用户默认提示音（同步返回）
   get defaultVoice() {
    return this.getLocalstorageValue('defaultVoice');
  }
  set defaultVoice(value) {
    this.setLocalstorageValue('defaultVoice', value);
  }

  // 用户信息（同步返回）
  get userinfo() {
    return this.getLocalstorageValue('userinfo');
  }
  set userinfo(value) {
    this.setLocalstorageValue('userinfo', value);
  }

  // 用户头像（同步返回）
  get userImg() {
    return this.getLocalstorageValue('userimg');
  }
  set userImg(value) {
    this.setLocalstorageValue('userimg', value);
  }

  // 登录密码（同步返回）
  get upwd() {
    return this.getLocalstorageValue('upwd');
  }
  set upwd(value) {
    this.setLocalstorageValue('upwd', value);
  }

  // 用户拥有的集团
  get companys(): Observable<any> {
    return new Observable(responseObserver => {
      this.getValue('companys', responseObserver);
    });
  }
  set companys(value) {
    this.setValue('companys', value);
  }

  // 用户功能点(同步)
  get functionPoint() {
    return this.getLocalstorageValue('functionPoint');
  }
  set functionPoint(value) {
    this.setLocalstorageValue('functionPoint', value);
  }

  // 当前公司(同步)
  get currentCompany() {
    return this.getLocalstorageValue('currentCompany');
  }
  set currentCompany(value) {
    this.setLocalstorageValue('currentCompany', value);
  }

  // 当前项目(同步)
  get currentProject() {
    return this.getLocalstorageValue('currentProject');
  }
  set currentProject(value) {
    this.setLocalstorageValue('currentProject', value);
    this.messageService.sendMessage(value, 'projectChange');             // 发送消息通知当前项目已改变
  }

  // 本地下载头像(同步)
  get headPortrait() {
    return this.getLocalstorageValue('headPortrait');
  }
  set headPortrait(value) {
    this.setLocalstorageValue('headPortrait', value);
    // this.messageService.sendMessage(value, 'avatar');             // 发送消息通知当前项目已改变
  }

  // 项目列表
  get projects(): Observable<any> {
    return new Observable(responseObserver => {
      this.getValue('projects', responseObserver);
    });
  }
  set projects(value) {
    this.setValue('projects', value);
  }

  // 一键部署
  get install(): Observable<any> {
    return new Observable(responseObserver => {
      this.getValue('install', responseObserver);
    });
  }
  set install(value) {
    this.setValue('install', value);
  }

   // 一键部署数据栈
   get stack(): Observable<any> {
    return new Observable(responseObserver => {
      this.getValue('stack', responseObserver);
    });
  }
  set stack(value) {
    this.setValue('stack', value);
  }

  // 用户信息（同步返回）
  get jpushstate() {
    return this.getLocalstorageValue('jpushstate');
  }
  set jpushstate(value) {
    this.setLocalstorageValue('jpushstate', value);
  }

  // 语音播报（同步返回）
  get voiceState() {
    return this.getLocalstorageValue('voiceState');
  }
  set voiceState(value) {
    this.setLocalstorageValue('voiceState', value);
  }

  getUrl(serviceCode, apiCode) {
    let ret;
    ret = {};
    if (this._configs) {
      const services = this._configs.services;
      for (let i = 0; i < services.length; i++) {
        const service = services[i];
        if (service.serviceCode === serviceCode) {
          // ret.serviceAddr = service.serviceAddr + '/';
          ret.serviceAddr = service.serviceAddr;
          for (let j = 0; j < service.apis.length; j++) {
            const api = service.apis[j];
            if (api.apiCode === apiCode) {
              ret.apiAddr = api.apiAddr;
            }
          }
        }
      }
    }

    return ret;
  }


  // 获取存储在storage中的数据,异步返回
  getValue(name, responseObserver) {
    const storeName = '_' + name;
    if (this[storeName]) {
      responseObserver.next(this[storeName]);
    } else {
      this.storage.get(storeName).then(val => {
        if (val) {
          try {
            this[storeName] = JSON.parse(val);
            responseObserver.next(this[storeName]);
          } catch (error) {
            responseObserver.next(null);
          }
        } else {
          responseObserver.next(null);
        }
        responseObserver.complete();
      });
    }
  }

  // 设置存储在storage中的数据,异步返回
  setValue(name, value) {
    const storeName = '_' + name;
    if (typeof value === 'string') {
      if (value === '') {
        this[storeName] = null;
        this.storage.remove(storeName);
      } else {
        this[storeName] = JSON.parse(value);
        this.storage.set(storeName, value);
      }
    } else if (typeof value === 'object') {
      this[storeName] = value;
      this.storage.set(storeName, JSON.stringify(value));
    }

    subject.next(value);
  }

  // 获取存储在localstorage中的数据,同步返回
  getLocalstorageValue(name) {
    const storeName = '_' + name;
    if (this[storeName]) {
      if (this.isJsonString(this[storeName])) {
        return JSON.parse(this[storeName]);
      }
      return this[storeName];
    } else {
      const val = localStorage.getItem(storeName);
      if (val) {
        if (this.isJsonString(val)) {
          this[storeName] = JSON.parse(val);
        } else {
          this[storeName] = val;
        }
        return this[storeName];
      } else {
        return null;
      }
    }
  }

  // 设置存储在localstorage中的数据
  setLocalstorageValue(name, value) {
    const storeName = '_' + name;
    if (typeof value === 'string') {
      if (value === '') {
        this[storeName] = null;
        localStorage.removeItem(storeName);
      } else {
        this[storeName] = value;
        localStorage.setItem(storeName, value);
      }
    } else if (typeof value === 'object') {
      this[storeName] = value;
      localStorage.setItem(storeName, JSON.stringify(value));
    }
    subject.next(value);
  }

  isJsonString(str) {
    try {
      if (typeof JSON.parse(str) === 'object') {
        return true;
      }
    } catch (e) {
    }
    return false;
  }

  clearCache() {
    for (const item in localStorage) {
      if (item) {
        console.log(item)
        // console.log(localStorage[item]);
        localStorage.removeItem(item);
      }
    }
    this.storage.clear();
  }


  // 获取该用户当前首页
  getCurrentIndexPage() {
    const functionPoint = this.functionPoint;
    console.log('功能点', functionPoint);
    let page;
    if (!functionPoint || functionPoint.length === 0) {
      page = 'home/page404';
      console.log('没有指定首页404');
    } else if (functionPoint.length === 3) {    // 运营人员
      page = 'home/indexOperation';
    } else if (functionPoint.length === 2) {    // 集团人员
      this.companys.subscribe(res => {
        this.currentCompany = res[0];
        page = 'home/indexGroup';
      });
    } else if (functionPoint.length === 1) {    // 项目人员
      this.companys.subscribe((res) => {
        this.currentCompany = res[0];
        page = 'home/indexProject';
      });
    }
    return page;
  }
}
